package org.gnyxy.service.impl;

import org.gnyxy.constant.DeleteConstant;
import org.gnyxy.constant.MessageConstant;
import org.gnyxy.constant.StatusConstant;
import org.gnyxy.context.BaseContext;
import org.gnyxy.entity.Collect;
import org.gnyxy.entity.Dish;
import org.gnyxy.entity.Material;
import org.gnyxy.exception.BaseException;
import org.gnyxy.mapper.CollectMapper;
import org.gnyxy.mapper.DishMapper;
import org.gnyxy.mapper.MaterialMapper;
import org.gnyxy.service.CollectService;
import org.gnyxy.vo.CollectVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CollectServiceImpl implements CollectService {
    @Autowired
    private CollectMapper collectMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private MaterialMapper materialMapper;

    /**
     * 新增收藏
     * @param dishId
     */
    @Override
    public void add(Long dishId) {
        if (dishId == null){
            throw new BaseException(MessageConstant.ID_IS_NULL);
        }
        Long userId = BaseContext.getCurrentId();
        Long dishNum = collectMapper.selectDishNumBydishId(dishId,userId);
        if (dishNum != null && dishNum > 0) throw new BaseException(MessageConstant.ALREADY_EXISTS);
        Collect collect = Collect.builder()
                .dishId(dishId)
                .userId(userId)
                .createTime(LocalDateTime.now())
                .deleted(DeleteConstant.IS_NOT_DELETED)
                .build();
        collectMapper.insert(collect);
    }

    /**
     * 删除收藏
     * @param id
     */
    @Override
    public void delete(Long id) {
        if (id == null){
            throw new BaseException(MessageConstant.ID_IS_NULL);
        }
        collectMapper.delete(id);
    }

    /**
     * 查看收藏的所有菜品
     * @return
     */
    @Override
    @Transactional
    public List<CollectVO> getAll() {
        Long userId = BaseContext.getCurrentId();
        // 查找收藏
        List<Collect> collects = collectMapper.getAllByUserId(userId);
        // 校验
        if (collects.isEmpty()) throw new BaseException("收藏为空");
        // 创建VO
        List<CollectVO> collectVOS = new ArrayList<>();
        // 分别创建dishId和materialId
        List<Long> dishIds = new ArrayList<>();
        List<Long> materialIds = new ArrayList<>();
        for (Collect collect : collects) {
            CollectVO collectVO = new CollectVO();
            BeanUtils.copyProperties(collect,collectVO);
            collectVOS.add(collectVO);
            if (collect.getDishId() != null) dishIds.add(collect.getDishId());
            if (collect.getMaterialId() != null)materialIds.add(collect.getMaterialId());
        }
        if (!dishIds.isEmpty()){
             List<Dish> dishes = dishMapper.getByIds(dishIds);
             if (dishes == null || dishes.isEmpty()) throw new BaseException("收藏为空");
             List<Long> deleteDishIds = new ArrayList<>();
            for (Dish dish : dishes) {
                if (dish == null || dish.getDeleted().equals(DeleteConstant.IS_DELETED) ||
                        dish.getStatus().equals(StatusConstant.DISABLE)){
                    deleteDishIds.add(dish.getId());
                }else {
                    for (CollectVO collectVO : collectVOS) {
                        if (collectVO.getDishId() != null &&
                                dish.getId().equals(collectVO.getDishId())){
                            collectVO.setName(dish.getName());
                            collectVO.setImage(dish.getImage());
                        }
                    }
                }
            }
            if (!deleteDishIds.isEmpty()){
                collectMapper.deleteByDishIds(deleteDishIds,userId);
            }
        }
        if (!materialIds.isEmpty()){
            List<Material> materials = materialMapper.getByIds(materialIds);
            List<Long> deleteMaterialIds = new ArrayList<>();
            for (Material material : materials) {
                if (material == null || material.getDeleted().equals(DeleteConstant.IS_DELETED) ||
                        material.getStatus().equals(StatusConstant.DISABLE)){
                    deleteMaterialIds.add(material.getId());
                }else {
                    for (CollectVO collectVO : collectVOS) {
                        if (collectVO != null && collectVO.getMaterialId() != null &&
                                material.getId().equals(collectVO.getMaterialId())){
                            collectVO.setName(material.getName());
                            collectVO.setImage(material.getImage());
                        }
                    }
                }
            }
            if (!deleteMaterialIds.isEmpty()){
                collectMapper.deleteByMaterialIds(materialIds,userId);
            }
        }

        return collectVOS.stream()
                .filter(collectVO -> collectVO != null && collectVO.getName() != null)
                .collect(Collectors.toList());
//        return collectMapper.getAll();
    }

    @Override
    public void addMaterial(Long materialId) {
        if (materialId == null){
            throw new BaseException(MessageConstant.ID_IS_NULL);
        }
        Long userId = BaseContext.getCurrentId();
        Long materialNum = collectMapper.selectMaterialNumByMaterialId(materialId,userId);
        if (materialNum != null && materialNum > 0) throw new BaseException(MessageConstant.ALREADY_EXISTS);
        Collect collect = Collect.builder()
                .materialId(materialId)
                .userId(BaseContext.getCurrentId())
                .createTime(LocalDateTime.now())
                .deleted(DeleteConstant.IS_NOT_DELETED)
                .build();
        collectMapper.insert(collect);
    }
}
